<?php
/**
 * Created by PhpStorm.
 * User: glq
 * Date: 2018/11/23
 * Time: 9:16
 */
namespace Question\Controller;

use Common\Controller\AdminbaseController;
use Label\Model\CategoryModel;
use Portal\Model\PostsModel;
use Think\Cache\Driver\Redis;

class AdminQuestionController extends AdminbaseController {

    protected $posts_model;
    protected $page_size;

    function _initialize() {
        parent::_initialize();
        $this->page_size    = 10;
        $this->posts_model  = D("Portal/Posts");
    }

    // 问答列表
    public function question_list()
    {
        $this->_lists(array("post_status" => array('neq', 3), 'post_type' => PostsModel::POST_TYPE_DISCUSSION_QUESTION));
        $this->display();
    }

    public function answer_list()
    {
        $this->_lists(array("post_status" => array('neq', 3), 'post_type' => PostsModel::POST_TYPE_DISCUSSION_ANSWER));
        $this->display();
    }

    // 问题编辑
    public function edit_question()
    {
        $pre        = "question_edit_";
        $id         = I('get.id', 0, 'intval');
        $key        = $pre . $id;
        $redis      = Redis::getinstance();
        $edit_id    = $redis->get($key);
        $admin_id   = session('ADMIN_ID');

        if ($edit_id && $edit_id != $admin_id) {
            $this->error('该问答正在被编辑，请稍后');
            exit;
        }

        $redis->set($key, $admin_id, C('POSTS_EDIT_TIME'));

        $post = $this->posts_model
            ->alias('p')
            ->where("id = $id")
            ->field('*, (select GROUP_CONCAT(name) FROM rx_label where FIND_IN_SET(id, p.labels) order by id) as label_names')
            ->find();
        if ($post && !empty($post['labels'])) {
            $post['label_names'] = array_filter(explode(',', $post['label_names']));
        } else {
            $post['label_names'] = [];
        }

        $post_categorys = M('category')->where(['type' => CategoryModel::CATEGORY_TYPE_QUESTION, 'status' => 1])->order('id asc')->select();
        $this->assign('post_categorys', $post_categorys);

        $this->assign("post", $post);
        $this->display();
    }

    // 修改问答
    public function updateQuestion()
    {
        if (IS_POST) {
            $post_id    = intval($_POST['post']['id']);
            $pre        = "questions_edit_";
            $key        = $pre . $post_id;
            $redis      = Redis::getinstance();
            $edit_id    = $redis->get($key);
            $admin_id   = session('ADMIN_ID');

            if ($edit_id && $edit_id != $admin_id) {
                $this->error('该问答正在被编辑，请稍后');
                exit;
            }
            $redis->del($key);

            $category = $_POST['post']['category'];
            if (empty($category)) {
                $this->error("请至少选择一个分类！");
            }
            $_POST['post']['category'] = implode(',', $category);

            $labels = $_POST['post']['labels'];
            $labels = array_filter(explode(',', $labels));
            if (empty($labels)) {
                $this->error("请至少选择一个标签！");
            }
            $_POST['post']['labels'] = implode(',', $labels);

            $_POST['post']['post_modified']= date("Y-m-d H:i:s",time());
            $question = I("post.post");
            $question['post_content'] = htmlspecialchars_decode($question['post_content']);
            $question['question_price'] = round(floatval($_POST['post']['question_price']),2);
            $result = $this->posts_model->save($question);
            if ($result !== false) {
                $this->success("保存成功！");
            } else {
                $this->error("保存失败！");
            }
        }
    }

    // 回答编辑
    public function edit_answer()
    {
        $pre        = "answer_edit_";
        $id         = I('get.id', 0, 'intval');
        $key        = $pre . $id;
        $redis      = Redis::getinstance();
        $edit_id    = $redis->get($key);
        $admin_id   = session('ADMIN_ID');

        if ($edit_id && $edit_id != $admin_id) {
            $this->error('该问答正在被编辑，请稍后');
            exit;
        }

        $redis->set($key, $admin_id, C('POSTS_EDIT_TIME'));

        $post = $this->posts_model
            ->alias('p')
            ->join('__USERS__ u on u.id = p.post_author')
            ->where("p.id = $id")
            ->field('p.*, u.user_nicename, (SELECT post_title FROM rx_posts WHERE id = p.question_id) as question_title')
            ->find();

        $this->assign("post",$post);
        $this->display();
    }

    // 修改回答
    public function update_answer()
    {
        if (IS_POST) {
            $post_id    = intval($_POST['post']['id']);
            $pre        = "answer_edit_";
            $key        = $pre . $post_id;
            $redis      = Redis::getinstance();
            $edit_id    = $redis->get($key);
            $admin_id   = session('ADMIN_ID');

            if ($edit_id && $edit_id != $admin_id) {
                $this->error('该问答正在被编辑，请稍后');
                exit;
            }
            $redis->del($key);


            $_POST['post']['post_modified']= date("Y-m-d H:i:s",time());
            $answer = I("post.post");
            $answer['post_content'] = htmlspecialchars_decode($answer['post_content']);
            $result = $this->posts_model->save($answer);
            if ($result !== false) {
                $this->success("保存成功！");
            } else {
                $this->error("保存失败！");
            }
        }
    }

    public function update_status()
    {
        $id     = I('get.id', 0, 'intval');
        $status = I('get.status', 0, 'intval');
        if ($id) {
            $this->posts_model->where(['id' => $id])->save(['post_status' => $status]);
            $this->success('成功更改状态');
        }
    }

    // 删除问答
    public function DelQuestion()
    {
        $post_id    = I('get.id', 0, 'intval');
        $pre        = "questions_edit_";
        $key        = $pre . $post_id;
        $redis      = Redis::getinstance();
        $edit_id    = $redis->get($key);
        $admin_id   = session('ADMIN_ID');

        if ($edit_id && $edit_id != $admin_id) {
            $this->error('该问答正在被编辑，请稍后');
            exit;
        }
        $redis->del($key);

        $this->posts_model->where(['id' => $post_id])->save(['post_status' => PostsModel::POST_STATUS_DEL]);
        $this->success('删除成功');
    }

    // 邀请专栏作者
    public function invite_professor()
    {
        $post_id = I('get.post_id', 0, 'intval');
        $this->pf_model = D('Professor/Professor');
        $where = array("p.del_time" => 0);
        if ($name = I("post.name")) {
            $where['u.user_nicename'] = array('like',"%$name%");
            $this->assign("name", $name);
        }

        $count  = $this->pf_model->alias('p')->join("__USERS__ u ON p.user_id = u.id")->where($where)->count();
        $page   = $this->page($count, $this->page_size);

        $this->pf_model
            ->alias("p")
            ->join("__QUESTION_INVITE__ q ON p.user_id = q.to_id and q.post_id = $post_id", 'left')
            ->join("__USERS__ u ON p.user_id = u.id", 'left')
            ->where($where)
            ->limit($page->firstRow , $page->listRows)
            ->field("p.id, p.user_id, u.user_nicename, u.user_login, u.position, u.company, q.id as id1, q.has_answer")
            ->order("id desc");

        $pf_lists = $this->pf_model->select();

        $this->assign("page", $page->show('Admin'));
        $this->assign("pf_list", $pf_lists);
        $this->assign('post_id', $post_id);
        $this->display();
    }

    // 邀请/取消邀请
    public function doInvite()
    {
        $type = I('get.type', 0, 'strval');
        $type = $type ? $type : 'del';

        if ($type == 'add') {
            $post_id    = I('get.post_id', 0, 'intval');
            $to_id      = I('get.to_id', 0, 'intval');
            $admin_id   = sp_get_current_admin_id();

            M('question_invite')->add(array(
                'post_id'       => $post_id,
                'invite_id'     => $admin_id,
                'to_id'         => $to_id,
                'created_at'    => time(),
            ));
        } else {
            $qi_id = I('get.qi_id', 0, 'intval');
            M('question_invite')->where(['id' => $qi_id])->delete();
        }
        $this->success('操作成功');
    }

    // 回答列表
    public function question_answer_list()
    {
        $post_id = I('post_id'); // 问答id
        if ($post_id) {
            $where = array(
                'p.question_id'       => $post_id,
                'p.post_status'       => array('neq', PostsModel::POST_STATUS_DEL),
                'p.post_type'         => PostsModel::POST_TYPE_DISCUSSION_ANSWER,
            );
            $answers = M('posts')
                ->alias('p')
                ->join('__USERS__ u on u.id = p.post_author', 'left')
                ->where($where)
                ->order('p.post_date desc')
                ->field('p.*, u.user_nicename')
                ->select();
            foreach ($answers as $k => $v) {
                $v['real_content'] = mb_substr(strip_tags($v['post_content']), 0, 50);
                $answers[$k] = $v;
            }
            $this->assign('answers', $answers);
            $this->assign('post_id', $post_id);
            $this->display();
        } else {
            $this->error('请输入正确ID');
        }
    }

    public function overview_question_answer()
    {
        $id = I('id', 0, 'intval');
        $post = M('posts')->where(['id' => $id])->find();
        $this->assign($post);
        $this->display();
    }

    public function delete_answer()
    {
        $id = I('id', 0, 'intval');
        M('posts')->where(['id' => $id])->save(['post_status' => PostsModel::POST_STATUS_DEL]);
        $this->success('删除成功');
    }

    /**
     * 问答列表处理方法,根据不同条件显示不同的列表
     * @param array $where 查询条件
     */
    private function _lists($where = array()) {

        $start_time = I('request.start_time');
        if(!empty($start_time)){
            $where['p.post_date'] = array(
                array('EGT', $start_time)
            );
        }

        $end_time = I('request.end_time');
        if(!empty($end_time)){
            if(empty($where['p.post_date'])){
                $where['p.post_date'] = array();
            }
            array_push($where['p.post_date'], array('ELT', $end_time));
        }

        $status = I('request.status');
        if($status >= 0){
            $where['p.post_status'] = $status;
        }

        $keyword = I('request.keyword');
        if(!empty($keyword)){
            $where['p.post_title'] = array('like', "%$keyword%");
        }

        $author = I('request.author');
        if(!empty($author)){
            $where['c.user_nicename'] = array('like', "%$author%");
        }

        $count  = $this->posts_model->alias('p')->join("__USERS__ c ON p.post_author = c.id")->where($where)->count();
        $page   = $this->page($count, 20);

        $questions = $this->posts_model
            ->alias("p")
            ->join("__USERS__ c ON p.post_author = c.id")
            ->where($where)
            ->limit($page->firstRow , $page->listRows)
            ->order("p.post_order DESC, p.post_date DESC")
            ->field("p.*, c.user_nicename, c.user_login, (SELECT post_title FROM rx_posts WHERE id = p.question_id) as question_title")
            ->select();

        foreach ($questions as $k => $q) {
            if (empty($q['user_nicename'])) {
                $q['user_nicename'] = $q['user_login'];
                $questions[$k] = $q;
            }
        }

        $this->assign("page", $page->show('Admin'));
        $this->assign("formget",array_merge($_GET, $_POST));
        $this->assign("questions",$questions);
    }

}